<template>
  <div class="root-table">
    <div class="table-operations">
      <a-row type="flex">
        <a-col :span="6" :order="4" class="a-col">
        </a-col>
        <a-col :span="6" :order="3" class="a-col">
        </a-col>
        <a-col :span="6" :order="2" class="a-col">
            <a-upload
              listType="picture"
              class="avatar-uploader"
              :showUploadList="false"
              :beforeUpload="beforeUpload"
            >
              <img v-if="imageUrl" class="avatar-picture" :src="imageUrl" alt="avatar"/>
              <div v-else>
                  <a-button>上传图片</a-button>
              </div>
            </a-upload>
        </a-col>
        <a-col :span="6" :order="1" class="a-col">
          <!-- <a-button @click="onDels">批量删除</a-button> -->
          <a-button @click="onRefresh">刷新</a-button>
        </a-col>
      </a-row>
    </div>
    <a-table :columns="columns"
      :rowKey="record => record.id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
    >
      <template slot="url" slot-scope="url">
        <img class="record-picture" :src="url"/>
      </template>
      <template slot="operation" slot-scope="text, record">
        <a @click="onDelete(record.id)" href="javascript:;">删除</a>
      </template>
    </a-table>
  </div>
</template>
<script>
import Vue from 'vue'
import serv from './ImageSearchService'
import { Button, Table, Col, Row, Upload } from 'ant-design-vue'
Vue.component(Upload.name, Upload)
Vue.component(Upload.name, Upload)
Vue.component(Row.name, Row)
Vue.component(Col.name, Col)
Vue.component(Table.name, Table)
Vue.component(Button.name, Button)

const columns = [{
  title: '名称',
  sorter: false,
  dataIndex: 'name',
  width: '10%'
}, {
  title: '图',
  dataIndex: 'url',
  width: '10%',
  scopedSlots: { customRender: 'url' }
}, {
  title: '图片签名',
  dataIndex: 'contSign'
}, {
  title: 'operation',
  dataIndex: '',
  scopedSlots: { customRender: 'operation' }
}]

export default {
  mounted () {
    // this.fetch({
    //   size: this.pagination.pageSize,
    //   page: this.pagination.current
    // })
  },
  computed: {
  },
  data () {
    return {
      data: [],
      pagination: {
        pageSize: 5,
        current: 1
      },
      selectedRowKeys: [],
      loading: false,
      columns,
      page: {},

      record: {},

      searchData: {},

      uploading: false,
      imageUrl: ''

    }
  },
  methods: {
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      if (!isJPG) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 3
      if (!isLt2M) {
        this.$message.error('Image must smaller than 3MB!')
      }
      const r = isJPG && isLt2M
      if (r) {
        this.$api.getBase64(file, (imageUrl) => {
          this.imageUrl = imageUrl
          this.uploading = false
        })
        this.pagination.current = 1
        this.fetch({
          size: this.pagination.pageSize,
          page: this.pagination.current,
          file: file
        })
        this.searchData.file = file
      }
      return false
    },
    onDelete (id) {
      const _this = this
      this.$confirm({
        title: '友情提示',
        content: '要删除这个图吗',
        onOk () {
          return new Promise((resolve, reject) => {
            serv.delete(id).then(res => {
              if (res.data.code === 0) {
                const dataSource = [..._this.data]
                _this.data = dataSource.filter(item => item.id !== id)
                resolve()
              } else {
                _this.$message.error(res.data.msg)
                resolve()
              }
            })
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel () {}
      })
    },
    onDels () {
      const _this = this
      this.$confirm({
        title: '友情提示',
        content: '要删除这些图吗',
        onOk () {
          return new Promise((resolve, reject) => {
            let formData = new FormData()
            formData.append('ids[]', _this.selectedRowKeys)
            serv.deleteForBatch(formData).then(res => {
              if (res.data.code === 0) {
                const dataSource = [..._this.data]
                _this.data = dataSource.filter(item => !_this.selectedRowKeys.includes(item.id))
                resolve()
              } else {
                _this.$message.error(res.data.msg)
                resolve()
              }
            })
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel () {}
      })
    },
    onRefresh () {
      this.pagination.current = 1
      // this.searchData = {}
      this.fetch({
        size: this.pagination.pageSize,
        page: this.pagination.current
      })
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    handleTableChange (pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      this.fetch({
        size: pagination.pageSize,
        page: pagination.current,
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
        ...this.searchData
      })
    },
    async fetch (params = {}) {
      this.loading = true
      this.page = await serv.getPage(params)
      const pagination = { ...this.pagination }
      pagination.total = this.page.totalElements
      // pagination.current = this.page.pageable.pageNumber + 1
      this.loading = false
      this.selectedRowKeys = []
      this.data = this.page.content
      this.pagination = pagination
    }
  }
}
</script>

<style scoped>
.root-table {
  height: 100%;
}
.table-operations {
  margin-bottom: 16px;
}

.table-operations > button {
  margin-right: 8px;
}

.a-col {
  padding: 0 20px;
}
.record-picture,
.avatar-picture {
  max-width: 50px;
  max-height: 50px;
}

.ant-upload-select-picture-card {
  width: none;
  height: none;
}
</style>
